package web.servlet.response;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 18148
 * @Date: 2020-05-20 13:48:55
 */
@WebServlet("/hW2_2")
public class HW2_2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.定义用户名和密码
         * 获取用户名和密码
         * 比较：
         *   若一致
         *   若不一致  把错误信息保存在域对象*/
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = "余斌";
        String pwd = "123";
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (name.equals(username) && pwd.equals(password)) {
            /*域对象:传递/共享
             * request域:在一次请求内传递/共享数据*/
            //req.setAttribute("user",username);
            /*getSession：在一次会话内*/
            req.getSession().setAttribute("user", username);
            /*重定向的url是给浏览器，让客户端浏览器去访问*/
            String path = req.getContextPath();
            resp.sendRedirect(path+"/homeWork2_2");
        } else {
            req.setAttribute("user", username);
            req.setAttribute("password", password);
            /*转发的url是给服务器用的*/
            req.getRequestDispatcher("/homeWork2_1").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
